<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="./libs/jquery-1.12.4.min.js"></script>
  </head>
  <body>
    <form action="">
      名字 <input name="name" type="text" /> <br />
      技能 <input name="skill" type="text" /> <br />
      故事 <input name="tale" type="text" /> <br />
      头像 <input name="wallpaper" type="file" id="files" /> <br />
      <img src="" alt="" />
      <input type="submit" value="提交" />
    </form>
  </body>
  <script>
    //图片改变
    $("#files").on("change", () => {
      //   let url = URL.createObjectURL($("#files")[0].files[0]);
      function getObjectURL(file) {
        let url = null;
        if (window.createObjectURL != undefined) {
          // basic
          url = window.createObjectURL(file);
        } else if (window.URL != undefined) {
          // mozilla(firefox)
          url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) {
          // webkit or chrome
          url = window.webkitURL.createObjectURL(file);
        }
        return url;
      }

      let objUrl = getObjectURL($("#files")[0].files[0]);
      if (objUrl) {
        $("form img").attr("src", objUrl);
      }
    });

    //提交表单
    $("form").on("submit", () => {
      const data = new FormData($("form")[0]);
      console.log(data);

      $.ajax({
        type: "post",
        url: "http://127.0.0.1:3000/add",
        data,
        processData: false,
        contentType: false,

        success: function(response) {
          console.log("提交成功");
        }
      });
      return false;
    });
  </script>
</html>
